package com.kongfuzi.student.ui.base;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.kongfuzi.student.support.utils.Util;


/**
 * Created by cfan_yang on 2015/12/9.
 */
public abstract class BasePopupWindow extends PopupWindow{

    private int mWidth;
    private int mHeight;
    protected View mConvertView;
    protected Context mContext;

    /**
     * 初始化PopupWindow
     * @param context
     * @param widthPercent PopupWindow宽度占屏幕百分比
     * @param heightPercent PopupWindow高度占屏幕百分比
     */
    public BasePopupWindow(Context context, float widthPercent, float heightPercent) {
        if(widthPercent<0 || widthPercent>1 || heightPercent<0 || heightPercent>1) {
            throw new IllegalArgumentException("percent must between 0 & 1");
        }
        this.mContext = context;
        calWidthANDHeight(context,widthPercent,heightPercent);
        mConvertView = View.inflate(context, getLayoutResourceId(),null);
        setContentView(mConvertView);
        if(mWidth == 0) {
            setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        } else {
            setWidth(mWidth);
        }
        if(mHeight == 0) {
            setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        } else {
            setHeight(mHeight);
        }

        setFocusable(true);
        setTouchable(true);
        setOutsideTouchable(true);
        setBackgroundDrawable(new BitmapDrawable());
        setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    dismiss();
                    return true;
                }
                return false;
            }
        });
        initView(context);
        initEvent();
    }

    protected abstract void initEvent();

    protected abstract void initView(Context context);

    /**
     * 获取填充此PopupWindow的布局文件的资源ID，由子类实现
     * @return
     */
    protected abstract int getLayoutResourceId();

    /**
     * 根据参数计算当前PopupWindow宽高
     * @param context
     * @param widthPercent
     * @param heightPercent
     */
    private void calWidthANDHeight(Context context,float widthPercent,float heightPercent) {
        mWidth = (int) (Util.getScreenWidthPixels(context) * widthPercent);
        mHeight = (int) (Util.getScreenHeightPixels(context) * heightPercent);
    }
}
